//
//  JBWEmoticonPageView.swift
//  新浪微博
//
//  Created by 季伯文 on 2017/7/11.
//  Copyright © 2017年 bowen. All rights reserved.
//

import UIKit

//cell重用标识
private let JBWEmoticonPageViewCellID = "JBWEmoticonPageViewCellID"

class JBWEmoticonPageView: UICollectionView {

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowlayout = UICollectionViewFlowLayout()
        
        //设置垂直和水平间距
        flowlayout.minimumLineSpacing = 0
        flowlayout.minimumInteritemSpacing = 0
        //滚动方向
        flowlayout.scrollDirection = .horizontal
        super.init(frame: frame, collectionViewLayout: flowlayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图
    private func setupUI(){
        
        dataSource = self
        register(JBWEmoticonPageViewCell.self, forCellWithReuseIdentifier: JBWEmoticonPageViewCellID)
        //在滚动到指定组和页数的时候 可能cell还没有实例化成功 使用主线程异步等到主线程任务完成后再再执行闭包中的代码
        DispatchQueue.main.async {
            //默认滚动到第一组第0页
            self.scrollToItem(at: IndexPath(item: 0, section: 1), at: UICollectionViewScrollPosition.left, animated: false)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //获取layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //设置itemsize
        layout.itemSize = self.frame.size
        
    }
}

//数据源方法
extension JBWEmoticonPageView: UICollectionViewDataSource{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return JBWEmoticonTools.share.allEmoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return JBWEmoticonTools.share.allEmoticons[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JBWEmoticonPageViewCellID, for: indexPath) as! JBWEmoticonPageViewCell
        cell.indexPath = indexPath
        cell.emoticons = JBWEmoticonTools.share.allEmoticons[indexPath.section][indexPath.item]
        return cell
    }
}
